package com.koron.operation.classes.shift.service.impl;


import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.koron.bean.base.Response;
import com.koron.operation.classes.shift.bean.po.ClassesShiftRecord;
import com.koron.operation.classes.shift.bean.po.ClassesTip;
import com.koron.operation.classes.shift.bean.query.ShiftQuery;
import com.koron.operation.classes.shift.bean.query.WorkFeignQuery;
import com.koron.operation.classes.shift.feign.ConfigureFeignService;
import com.koron.operation.classes.shift.mapper.ClassesTipMapper;
import com.koron.operation.classes.shift.service.ClassesShiftRecordService;
import com.koron.operation.classes.shift.service.ClassesTipService;
import org.koron.ebs.mybatis.SessionFactory;
import org.koron.ebs.mybatis.TaskAnnotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 交接事项(ClassesTip)表服务实现类
 *
 * @author jzp
 * @since 2021-10-27 18:36:23
 */
@Service
public class ClassesTipServiceImpl implements ClassesTipService {

    @Autowired
    private ConfigureFeignService configureFeignService;

    @Autowired
    private ClassesShiftRecordService classesShiftRecordService;

    /**
     * 通过ID查询单条数据
     */
    @Override
    @TaskAnnotation("getById")
    public ClassesTip getById(SessionFactory factory, String id) {
        ClassesTipMapper mapper = factory.getMapper(ClassesTipMapper.class);
        return mapper.selectById(id);
    }

    /**
     * 查询所有数据
     */
    @Override
    @TaskAnnotation("list")
    public List<ClassesTip> list(SessionFactory factory, ClassesTip classesTip) {
        ClassesTipMapper mapper = factory.getMapper(ClassesTipMapper.class);
        return mapper.selectList(classesTip);
    }

    @Override
    @TaskAnnotation("listByRecordId")
    public List<ClassesTip> listByRecordId(SessionFactory factory, String recordId) {
        ClassesTip tip = new ClassesTip();
        tip.setRecordId(recordId);
        List<ClassesTip> list = list(factory, tip);
        IntStream.range(0, list.size()).filter(i -> list.get(i).getSort() == null).forEach(i -> list.get(i).setSort(i+100));
        list.sort(Comparator.comparing(ClassesTip::noNullSort));
        return list;
    }

    @Override
    @TaskAnnotation("getMaxSort")
    public int getMaxSort(SessionFactory factory, String recordId, String firstLevel, String secondLevel) {
        ClassesTip classesTip = new ClassesTip();
        Assert.hasText(recordId, "recordId不能为空");
        classesTip.setRecordId(recordId);
        classesTip.setFirstLevel(firstLevel);
        classesTip.setSecondLevel(secondLevel);
        ClassesTipMapper mapper = factory.getMapper(ClassesTipMapper.class);
        Integer integer = mapper.selectMaxSort(classesTip);
        return integer == null ? 0 : integer;
    }

    @Override
    @TaskAnnotation("getMergeMaxSort")
    public int getMergeMaxSort(SessionFactory factory, ClassesTip classesTip) {
        int secondSort = getMaxSort(factory, classesTip.getRecordId(), classesTip.getFirstLevel(), classesTip.getSecondLevel());
        if (secondSort > 0) {
            return secondSort;
        }
        int firstSort = getMaxSort(factory, classesTip.getRecordId(), classesTip.getFirstLevel(), null);
        if (firstSort > 0) {
            return firstSort;
        }
        return getMaxSort(factory, classesTip.getRecordId(), null, null);
    }

    @Override
    @TaskAnnotation("setMaxSort")
    public void setMaxSort(SessionFactory factory, ClassesTip classesTip) {
        if (classesTip.getSort() != null) {
            return;
        }
        int maxSort = getMergeMaxSort(factory, classesTip);
        ClassesTipMapper mapper = factory.getMapper(ClassesTipMapper.class);
        classesTip.setSort(++maxSort);
        mapper.rollSort(classesTip.getRecordId(), maxSort);
    }

    @Override
    @TaskAnnotation("getByCondition")
    public List<ClassesTip> getByCondition(SessionFactory factory, String shiftId, WorkFeignQuery extractWorkFeignQuery) {
        // 找到上一个交接班记录
        ShiftQuery shiftQuery = new ShiftQuery();
        shiftQuery.setNextShiftId(shiftId);
        ClassesShiftRecord one = classesShiftRecordService.getOne(factory, shiftQuery);
        if (one != null) {
            return listByRecordId(factory, one.getId());
        }
        // 如果没有，则找交接班配置
        return getFeignByCondition(extractWorkFeignQuery);
    }

    @Override
    public List<ClassesTip> getFeignByCondition(WorkFeignQuery query) {
        List<ClassesTip> tips = new ArrayList<>();
        /*
         * A 值班长+值班员、B 值班员、C 值守、D OnCall
         * 0 值班长+值班员、2 值班员、1 值守、3 OnCall
         */
        String onduty = "";
        switch (query.getStaffType()) {
            case "0":
                onduty = "A";
                break;
            case "1":
                onduty = "C";
                break;
            case "2":
                onduty = "B";
                break;
            case "3":
                onduty = "D";
                break;
        }
        Response<Object> objectResponse = configureFeignService.queryList(query.getDeptId(), query.getLocationId(), onduty);
        JSONArray array = JSONArray.parseArray(JSONArray.toJSONString(objectResponse.getData()));
        for (int i = 0; i < array.size(); i++) {
            JSONObject jsonObject = array.getJSONObject(i);
            tips.add(fromJson(jsonObject));
        }
        tips.sort(Comparator.comparingInt(ClassesTip::noNullSort));
        return tips;
    }

    /**
     * 新增数据
     */
    @Override
    @TaskAnnotation("save")
    public boolean save(SessionFactory factory, ClassesTip classesTip) {
        checkTip(classesTip);
        ClassesTipMapper mapper = factory.getMapper(ClassesTipMapper.class);
        if (classesTip.getSort() == null) {
            setMaxSort(factory, classesTip);
        }

        // 如果是更新
        if (!StringUtils.isEmpty(classesTip.getId())) {
            // 如果一级项有修改，相同的一级项全部进行修改
            ClassesTip source = getById(factory, classesTip.getId());
            Assert.notNull(source, "根据id：" + classesTip.getId() + "找不到配置");
            if (!source.getFirstLevel().equals(classesTip.getFirstLevel())) {
                mapper.updateByFirstLevel(classesTip.getRecordId(), source.getFirstLevel(), classesTip.getFirstLevel());
            }
        }

        return mapper.insertOrUpdate(classesTip) > 0;
    }

    @Override
    @TaskAnnotation("insert")
    public boolean insert(SessionFactory factory, ClassesTip classesTip) {
        checkTip(classesTip);
        Assert.notNull(classesTip.getSort(), "插入时排序号不能为空");
        ClassesTipMapper mapper = factory.getMapper(ClassesTipMapper.class);
        mapper.rollSort(classesTip.getRecordId(), classesTip.getSort());
        return mapper.insertOrUpdate(classesTip) > 0;
    }

    @Override
    @TaskAnnotation("saveBatch")
    public boolean saveBatch(SessionFactory factory, List<ClassesTip> tips) {
        if (CollectionUtils.isEmpty(tips)) {
            return false;
        }
        for (ClassesTip tip : tips) {
            checkTip(tip);
        }
        ClassesTipMapper mapper = factory.getMapper(ClassesTipMapper.class);
        return mapper.insertOrUpdateBatch(tips) > 0;
    }

    /**
     * 修改数据
     */
    @Override
    @TaskAnnotation("update")
    public boolean update(SessionFactory factory, ClassesTip classesTip) {
        checkTip(classesTip);
        ClassesTipMapper mapper = factory.getMapper(ClassesTipMapper.class);
        return mapper.update(classesTip) > 0;
    }

    /**
     * 通过主键删除数据
     */
    @Override
    @TaskAnnotation("deleteBatchIds")
    public boolean deleteBatchIds(SessionFactory factory, List<String> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return false;
        }
        ClassesTipMapper mapper = factory.getMapper(ClassesTipMapper.class);
        return mapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 通过recordId删除数据
     */
    @Override
    @TaskAnnotation("removeByRecordId")
    public boolean removeByRecordId(SessionFactory factory, String recordId) {
        if (StrUtil.isEmpty(recordId)) {
            return false;
        }
        ClassesTip classesTip = new ClassesTip();
        classesTip.setRecordId(recordId);
        List<ClassesTip> list = list(factory, classesTip);

        return deleteBatchIds(factory, list.stream().map(ClassesTip::getId).collect(Collectors.toList()));
    }

    private ClassesTip fromJson(JSONObject jsonObject) {
        ClassesTip tip = new ClassesTip();
        tip.setConfigureId(jsonObject.getString("id"));
        tip.setFirstLevel(jsonObject.getString("firstLevel"));
        tip.setSecondLevel(jsonObject.getString("secondLevel"));
        tip.setContent(jsonObject.getString("content"));
        tip.setDisplayFlag(jsonObject.getBoolean("displayFlag"));
        tip.setSort(jsonObject.getInteger("sort"));
        return tip;
    }

    private void checkTip(ClassesTip classesTip) {
        Assert.isTrue(!"\n".equals(classesTip.getContent()), classesTip.getSecondLevel() + "的内容不能为一个换行符");
    }
}
